<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ChevronLeftSharp } from '@vicons/material'
  import { NIcon, NButton, NForm, NFormItem, NInput, NSpin, useMessage } from 'naive-ui'
  import WordPreview from '@/components/WordPreview/index.vue'
  import {
    generateScheme,
    getSchemeAuditDetail,
    getTemplateParamList,
    submitAudit,
  } from '@/api/scheme'
  import { createChat } from '@/api/agent'
  import { getContent } from '../Build/utils'
  import AuditModal from './components/AuditModal.vue'
  import { useAgent } from '@/hooks/useAgent'
  const router = useRouter()
  const route = useRoute()
  const type = route.params.type
  const id = route.query.id as string
  const libId = route.query.libId as string
  const file = ref()
  const templateId = ref()
  const formList = ref<any[]>([])
  const agentKeys = ref<any>({})
  const loading = ref(false)
  const schemeName = ref('')
  const formData = reactive<any>({})
  const categoryName = ref('')
  const wordPreviewId = ref(`${new Date().getTime()}`)
  const { userName } = useAgent()
  onMounted(async () => {
    await init()
  })

  // 构建输入参数
  const buildInputs = (params?: any) => {
    const inputs: any = {}
    if (params) {
      inputs.file_name = params.file_name
      inputs.subcategory = params.subcategory
      inputs.Category_plan = params.Category_plan
      inputs.file_path = ''
    }
    return inputs
  }

  const init = async () => {
    if (type === '1') {
      await initAgent()
    } else {
      await initScheme()
    }
  }

  const initScheme = async () => {
    const res = await getSchemeAuditDetail({ schemeId: id })
    if (res) {
      file.value = res.schemeUrl
      templateId.value = res.categoryType
      await getTemplateList()
    }
  }

  const initAgent = async () => {
    loading.value = true
    const gen2Obj = localStorage.getItem('gen2Obj')
    if (gen2Obj) {
      try {
        const res = JSON.parse(gen2Obj)
        file.value = res.gen2Obj?.path
        schemeId.value = res.gen2Obj?.id
        // file.value = 'http://192.168.14.110:4567/体检报告.doc'
        templateId.value = res.gen2Obj?.categoryType
        schemeName.value = res.gen2Obj?.schemeName
        if (templateId.value) {
          await getTemplateList()
        }
        if (res.inputs) {
          categoryName.value = res.inputs.subcategory
          libraryId.value = res.inputs.libraryId
          // 发送信息给智能体
          const inputs = buildInputs(res.inputs)
          // console.log(inputs)
          const content = await createChat({
            query: '继续',
            userName,
            responseMode: 'streaming',
            conversationId: res.conversationId ?? undefined,
            inputs,
          })
          const paramsResult = getContent(content.answer)
          agentKeys.value = JSON.parse(paramsResult.content)
          Object.keys(agentKeys.value).forEach((key: string) => {
            formData[key] = agentKeys.value[key]
          })
        }
        loading.value = false
      } catch (error) {
        console.log(error)
        loading.value = false
      }
    }
  }

  const getTemplateList = async () => {
    const templateList = await getTemplateParamList({ id: templateId.value })
    formList.value = templateList
    templateList.forEach((item: any) => {
      formData[item.key] = undefined
    })
  }
  const handleBack = () => {
    router.back()
  }

  // const page = ref(1)
  // const pageSize = ref(10)
  // const itemCount = ref(100)

  // const handleUpdatePageSize = (_pageSize: number) => {
  //   pageSize.value = _pageSize
  //   page.value = 1
  // }

  // const handleUpdatePage = (_page: number) => {
  //   page.value = _page
  // }
  const reset = () => {
    Object.keys(formData).forEach((key: string) => {
      formData[key] = agentKeys.value[key] ?? undefined
    })
  }
  const formRef = ref()
  const message = useMessage()

  const schemeId = ref()
  const handleSave = () => {
    formRef.value?.validate(async (errors: any) => {
      if (!errors) {
        const path = file.value
        file.value = undefined
        const res = await generateScheme({
          schemeName: schemeName.value,
          categoryName: formData.subcategory,
          categoryType: templateId.value,
          path,
          paramMap: formData,
          id: schemeId.value,
        })
        message.success('保存成功')
        console.log(res)
        wordPreviewId.value = `${new Date().getTime()}`
        file.value = res.schemeUrl
        // file.value = 'http://192.168.14.110:4567/节日保电方案模板.docx'
        schemeId.value = res.id
      }
    })
  }

  const validator = (rule: any, value: any): any => {
    return new Promise<void>((resolve, reject) => {
      if (value) {
        resolve()
      } else {
        reject(new Error(`请输入${rule.label}`))
      }
    })
  }

  const handleSubmit = () => {
    formRef.value?.validate(async (errors: any) => {
      if (!errors) {
        auditModalRef.value?.handleOpen()
      }
    })
  }

  const libraryId = ref(libId)
  const auditModalRef = ref()
  const submitAuditFn = async (data: any) => {
    await submitAudit({
      auditorId: data.auditUser,
      schemeName: schemeName.value,
      schemeId: schemeId.value,
      remarks: data.remark,
      type: 1,
    })
    message.success('提交审核成功')
    await router.push(`/createScheme/${libraryId.value}`)
  }
</script>

<template>
  <div class="h-full p-5 pingfang">
    <div class="h-full bg-white rounded flex">
      <div class="w-[50%]">
        <div class="h-[68px] flex items-center px-5 justify-between border-b border-b-[#F0F0F0]">
          <div class="flex items-center">
            <div
              class="pingfang flex text-[#0B5CFF] border border-[#0B5CFF] rounded hover:text-[#0B5CFFCC] items-center px-3 cursor-pointer h-8 leading-8"
              @click="handleBack"
            >
              <n-icon>
                <ChevronLeftSharp />
              </n-icon>
              <div class="font-medium ml-1">返回</div>
            </div>
            <div class="ml-4 font-bold text-[20px]">原文概览</div>
          </div>
          <div></div>
        </div>
        <div
          class="h-[calc(100%-120px)] border-b border-b-[#F0F0F0] border-r border-r-[#F0F0F0] px-5 py-6"
        >
          <WordPreview
            :key="file"
            v-if="file"
            mode="view"
            :file="file"
            :id="wordPreviewId"
            :userName="userName"
          />
        </div>
      </div>

      <div class="w-[50%]">
        <n-spin class="h-full" :show="loading">
          <div class="h-[68px] flex items-center px-5 justify-between border-b border-b-[#F0F0F0]">
            <div class="flex items-center">
              <div class="ml-4 font-bold text-[20px]">文章切片</div>
            </div>
            <div class="flex items-center gap-4">
              <n-button type="primary" @click="handleSubmit"> 提交审核 </n-button>
              <n-button @click="handleSave" class="!border-[#0B5CFF]">保存</n-button>
              <n-button @click="reset">重置</n-button>
            </div>
          </div>
          <div class="h-[calc(100%-120px)] border-b border-b-[#F0F0F0] px-5 py-6 overflow-y-auto">
            <n-form :model="formData" ref="formRef" require-mark-placement="left">
              <n-form-item
                :rule="{
                  required: true,
                  message: `请输入${item.name}`,
                  trigger: ['input'],
                  validator,
                }"
                required
                v-for="item in formList"
                :key="item.key"
                :label="item.name"
                :path="item.key"
              >
                <n-input
                  :placeholder="`请输入${item.name}`"
                  v-if="item.type === 1"
                  v-model:value="formData[item.key]"
                />
              </n-form-item>
            </n-form>
          </div>
          <div class="h-6 mt-3 flex justify-between items-center">
            <div></div>
            <!-- <n-pagination
            show-quick-jumper
            v-model:page="page"
            :page-size="pageSize"
            :item-count="itemCount"
            :page-sizes="[10, 20, 50]"
            show-size-picker
            :on-update-page-size="handleUpdatePageSize"
            :on-update-page="handleUpdatePage"
          >
            <template #prefix="{ itemCount }">
              <span class="pingfang text-[#666D7A]">共 {{ itemCount }} 条</span>
            </template>
<template #suffix>
              <span class="pingfang text-[#666D7A]">页</span>
            </template>
</n-pagination> -->
          </div>
        </n-spin>
      </div>
    </div>
    <AuditModal ref="auditModalRef" @submit="submitAuditFn" />
  </div>
</template>

<style lang="less" scoped>
  :deep(.n-spin-container) {
    height: 100%;
  }

  :deep(.n-spin-content) {
    height: 100%;
  }
</style>
